package com.hontech.bread.store

import androidx.core.database.sqlite.transaction
import com.hontech.bread.utils.runCPU
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
class StoreAdv(
    val id: Long,

    @SerialName("adv_type")
    val advType: Int,

    val name: String,

    @SerialName("create_timestamp")
    val createTimestamp: Long
) {

    companion object {
        const val TYPE_UNKNOWN = 0
        const val TYPE_VIDEO = 1
        const val TYPE_IMAGE = 2

        const val CREATE_SQL = "CREATE TABLE IF NOT EXISTS tb_adv (" +
                "id INTEGER PRIMARY KEY, " +
                "adv_type INTEGER NOT NULL, " +
                "name TEXT NOT NULL, " +
                "create_timestamp INTEGER NOT NULL" +
                ")"

        suspend fun query() = runCPU {
            val list = ArrayList<StoreAdv>()
            val cursor = Store.db.rawQuery(
                "SELECT id, adv_type, name, create_timestamp FROM tb_adv",
                arrayOf()
            )
            cursor.use {
                while (cursor.moveToNext()) {
                    val adv = StoreAdv(
                        cursor.getLong(0),
                        cursor.getInt(1),
                        cursor.getString(2),
                        cursor.getLong(3)
                    )
                    list.add(adv)
                }
            }
            list
        }
    }

    fun isImage() = advType == TYPE_IMAGE
    fun isVideo() = advType == TYPE_VIDEO

    suspend fun create() = runCPU {
        Store.db.transaction {
            execSQL("DELETE FROM tb_adv WHERE id = ?", arrayOf(id))
            execSQL(
                "INSERT INTO tb_adv (id, adv_type, name, create_timestamp) VALUES (?, ?, ?, ?)",
                arrayOf(
                    id, advType, name, createTimestamp
                )
            )
        }
    }

    suspend fun delete() = runCPU {
        Store.db.execSQL("DELETE FROM tb_adv WHERE id = ?", arrayOf(id))
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as StoreAdv

        return id == other.id
    }

    override fun hashCode(): Int {
        return id.hashCode()
    }


}


















